package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import entity.Prod;
import util.RowMapper;
import util.UtilDB;

public class ProdDao {
	private UtilDB<Prod> pdb=new UtilDB<Prod>();
	
	public boolean add(Prod prod){
		String sql = "insert into prod(prodname,price) values(?,?)";
		return pdb.executeSQL(sql, prod.getProdname(),prod.getPrice());		
	}

	public boolean del(int id) {
		String sql = "delete from prod where id=?";
		return pdb.executeSQL(sql,id);
	}
	
	public boolean update(Prod prod) {
		String sql = "update prod set prodname=?,price=? where id=?";
		return pdb.executeSQL(sql, prod.getProdname(),prod.getPrice(), prod.getId());
	}
	
	public Prod findProdById(int id) {
		String sql = "select id,prodname,price from prod where id=?";
		return pdb.executeQueryForObject(sql, new ProdRowMapper(), id);
	}
	
	public Prod findProdByName(String prodname) {
		String sql = "select id,price from prod where prodname=?";
		return pdb.executeQueryForObject(sql, new ProdRowMapper(), prodname);
	}

	public List<Prod> findAllProd() {
		String sql="select id,prodname,price from prod";
		return pdb.executeQueryForList(sql, new ProdRowMapper());
	}

	private class ProdRowMapper implements RowMapper<Prod> {

		public Prod rowMapper(ResultSet rs) throws SQLException {
			Prod prod=new Prod();
			prod.setId(rs.getInt("id"));
			prod.setProdname(rs.getString("prodname"));
			prod.setPrice(rs.getFloat("price"));
			return prod;
		}

	}

}
